#include <unistd.h>
#include <cstdio>
#include <string>
#include <cerrno>
#include <iostream>
#include <fcntl.h>
#include <sys/select.h>

void SetNonBlocking(int fd)
{
    int f1 = fcntl(fd, F_GETFL);
    if(f1 < 0)
    {
        perror("fcntl(F_GETFL)");
        return;
    }
    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
}

int main() 
{
    fd_set rfds;
    std::string tips = "Please enter# ";
    char buffer[1024];
    SetNonBlocking(0);
    while(true)
    {
        write(1, tips.c_str(), tips.size());
        // 非阻塞，如果我们不做输入，数据不就绪，以出错形式返回！！！
        int n = read(0, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "read file end!" << std::endl;
            break;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "no data available, try again later" << std::endl;
                sleep(1);
                
                continue;
            }
            else if (errno == EINTR)
            {
                std::cout << "system call interrupted, try again later" << std::endl;
                sleep(1);
                
                continue;
            }
            else
            {
                std::cout << "read error: " << n << " errno: " << errno <<std::endl;
            }
        }
        sleep(1);
    }
}